
package com.sunway.resource2es.service;


import com.sunway.annotations.ddss.DbName;
import com.sunway.annotations.ddss.DyDS;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 数据库操作
 *
 * @author lxw
 * @version V1.0
 * @date 2024-7-18
 */
//@Slf4j
@Service
public class JdbcSqlServiceImpl {

    private static final Logger log = LoggerFactory.getLogger(JdbcSqlServiceImpl.class);

    private final JdbcTemplate jdbcTemplate;

    public JdbcSqlServiceImpl(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    /**
     * 查询表中数据
     *
     * @param tableName 表名
     * @param condition 条件
     * @return java.lang.Long
     * @author lxw
     * @date 2024/12/9 9:17
     **/
    @DyDS
    public Long getTableCount(@DbName String dbName,String tableName, String condition) {
        String sql = "select count(1) from " + tableName;
        if (StringUtils.isNotBlank(condition)) {
            sql += " where " + condition;
        }
        return jdbcTemplate.queryForObject(sql, Long.class);
    }

    /**
     * 查询数据
     *
     * @param tableName   表名
     * @param condition   条件
     * @param lastId      上次ID
     * @param cardinality 每次查询数量
     * @return java.util.List<java.util.Map < java.lang.String, java.lang.Object>>
     * @author lxw
     * @date 2024/12/9 9:17
     **/
    @DyDS
    public List<Map<String, Object>> fetchData(@DbName String dbName, String tableName, String condition, String lastId, int cardinality) {
        String sql = "select * from " + tableName + " a where a.id >" + lastId;
        try {
            if (StringUtils.isNotBlank(condition)) {
                sql += "  and " + condition + " ";
            }
            sql += " ORDER BY a.id limit 0," + cardinality;
            log.info("===> log-info: 数据查询sql: {}", sql);
            return jdbcTemplate.queryForList(sql);
        } catch (DataAccessException e) {
            log.error("===> log-error: {}数据表查询数据错误: {}", tableName, e.getMessage());
            return new ArrayList<>();
        }
    }


}
